IHG.Toolbar = function(element)
{	
	if(!element || (element && element.className.indexOf('IHGUBBBar') != -1)) {
		return;
	}
	
	var _self = this;
	
	this.tab = //String.fromCharCode(0x09);
	this.tab = '    '; // vier spaties
	this.cache = {};
	this.toolbarButtons = [];
	
	this.txtarea = $(element);
	this.container = document.createElement('div');
	this.container.className = 'IHGUBBContainer';
	this.selectionController = new IHG.SelectionController(element);
	
	with(this.txtarea) {
		className += ' IHGUBBBar';
		
		
		this.txtarea.on('keydown', function(e) {
			return _self.keyWatcher(e || window.event);
		});
		
		this.txtarea.on('mouseup', function(e) {
			_self.refresh();
		});
		
		this.txtarea.on('keyup', function(e) {
			if(_self.keyUpTimeout) {
				clearTimeout(_self.keyUpTimeout);
			}
			
			_self.keyUpTimeout = setTimeout(function() {
				_self.refresh()
			}, 50); // "Snappy-heid" van de knopskes
		});
		
		this.txtarea.on('keypress', function(e)
		{
			/* dirty little hack om tab-knop in Firefox af te vangen */
			if(e && e.keyCode == 9) return false;
		});
	}
	
	this.bar = document.createElement('ul');
	this.bar.className = 'IHGUBBBar';

	this.txtarea.parentNode.insertBefore(this.container, this.txtarea);

	this.container.appendChild(this.bar);
	this.container.appendChild(this.txtarea);

	// let op, deze namen moeten overeenkomen met IHGUBBBar.
	this.keyRegister = [];
	
	// Internet Explorer is kut. Soms.
	if(IHG.SelectionController.model == 'w3c') {
		this.keyRegister[IHG.Toolbar.Keys.ENTER] =  function(sender, e) // OK
		{
			var indentSpaces = '';
			var selStart = sender.selectionController.start();
			var leadingText = sender.txtarea.value.substr(0, selStart);
			var lastEnter = leadingText.lastIndexOf('\n');

			if(lastEnter > 0) {
				var currentPosition = lastEnter + 1;
				while(leadingText.substr(currentPosition, sender.tab.length) == sender.tab) {
					currentPosition+= sender.tab.length;
					indentSpaces += sender.tab;
				}
			}
			
			setTimeout(function() {
				sender.selectionController.wrap(indentSpaces, '');
			}, 1);
			
			throw IHG.IGNORE;
		}
		
		this.keyRegister[IHG.Toolbar.Keys.SHIFT + IHG.Toolbar.Keys.ENTER] = function(sender, e)
		{
			sender.txtarea.form.submitForm();
		}
		
		this.keyRegister[IHG.Toolbar.Keys.TAB] = function(sender, e) // OK
		{
			sender.selectionController.wrap(sender.tab, '');
		}
		
		this.keyRegister[IHG.Toolbar.Keys.BACKSPACE] = function(sender, e)
		{
			var start = sender.selectionController.start();
			var end = sender.selectionController.end();
			var txt = sender.txtarea.value;
			
			if(start !== end) throw IHG.IGNORE;
			
			if(txt.substr(start - sender.tab.length, sender.tab.length) == sender.tab) {
				sender.txtarea.value = txt.substr(0, start - sender.tab.length) + txt.substr(start);
				sender.selectionController.move(start - sender.tab.length);
			} else {
				throw IHG.IGNORE;
			}
		}
	}
}

IHG.Toolbar.VERSION 		= 16;

IHG.Toolbar.DISABLED 	= 0;
IHG.Toolbar.ENABLED 		= 1;
IHG.Toolbar.ACTIVE 		= 2;

IHG.Toolbar.Keys = {
	CMD: 			'[ctrl] + ',
	SHIFT: 		'[shift] + ',
	ENTER: 		'[enter]',
	TAB: 			'[tab]',
	BACKSPACE: 	'[backspace]'
}

IHG.Toolbar.initWithDefaults = function(txtarea)
{
	var bar = new IHG.Toolbar(txtarea);
	bar.refresh(_IHGToolbarButtons);
	return bar;
}

IHG.Toolbar.prototype = {
	carrotIsBetween: function()
	{
		return true;
	},
	
	position: function()
	{
		var obj = this.txtarea;
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}
		
		return {
			x: curleft,
			y: curtop
		};
	},
	
	addButton: function(toolbarButton)
	{
		var _self = this;		
		
		this.toolbarButtons.push(toolbarButton);
		if(toolbarButton.tag) {
			this.selectionController.tags.push(toolbarButton.tag);
		}	
		
		/* let op het 2e argument: deze dwingt het teruggeven van een DOMNode af */
		var buttonNode = toolbarButton.draw(this, this.bar);
		
		if(buttonNode) {
			/* click-afvanger aan het knopje hangen */
			$(buttonNode).on('click', (function(button) {
				return function(sender) {
					_self.clickWatcher(sender, button);
					return false;
				}
			})(toolbarButton));
		}
		
		if(toolbarButton.shortcut) {
			/* shortcut-key opslaan in register */
			this.keyRegister[toolbarButton.shortcut] = function() {
				toolbarButton.trigger.apply(toolbarButton, arguments);
			}
		}
	},

	clickWatcher: function(e, toolbarButton)
	{
		toolbarButton.trigger(this);
		this.refresh();
	},

	keyWatcher: function(e) // Moet nog opgeruimd worden
	{
		/*var txt = '';// = 'Key:\n';
		txt += 'e.charCode: ' + e.charCode + ', ';// (' + String.fromCharCode(e.charCode) + ')\n';
		txt += 'e.which: ' + e.which + ', ';
		//txt += 'fromCharCode: ' + String.fromCharCode(e.charCode) + '\n';
		txt += 'e.keyCode: ' + e.keyCode;
		//txt += 'e.shiftKey: ' + e.shiftKey + '\n';
		//txt += 'e.ctrlKey: ' + e.ctrlKey + '\n';
		//txt += 'e.metaKey: ' + e.metaKey + '\n';
		this.txtarea.value = txt;
		// */
	
		var key = '';
		
		if(e.metaKey || e.ctrlKey) {
			key += IHG.Toolbar.Keys.CMD;
		}
		
		if(e.shiftKey) {
			key += IHG.Toolbar.Keys.SHIFT;
		}
				
		if(e.keyCode == 13) {
			key += IHG.Toolbar.Keys.ENTER;
		} else if(e.keyCode == 9) {
			key += IHG.Toolbar.Keys.TAB;
		} else if(e.keyCode == 8) {
			key += IHG.Toolbar.Keys.BACKSPACE;
		} else {
			 key += String.fromCharCode(e.which || e.keyCode).toLowerCase();
			// toLowerCase() tegen rekjes met hoofdletters, zoals het overigens volgens de specs ook hoort.
		}
				
		if(this.keyRegister[key]) {
			try {
				this.keyRegister[key](this, e);
				this.refresh();
								
				return false;
			} catch(e) {
				if(e === IHG.IGNORE)
					return true;
				else 
					throw e;
			}
		}
	},
	
	refresh: function(buttons)
	{
		this.selectionController.cache.clear();
		
		if(buttons) {
			for(var i = 0; i < buttons.length; i++) {
				try {
					for(var j = this.toolbarButtons.length - 1; j >= 0; j--) {
						if(buttons[i].id === this.toolbarButtons[j].id) {
							throw IHG.IGNORE;
						}
					}
					
					var button = IHG.clone(buttons[i]);
					this.addButton(button);
				} catch(e) {}
			}
		}
		
		for(i = 0; i < this.toolbarButtons.length; i++) {
			this.toolbarButtons[i].draw(this, null);
		}
	}
}